<template>
  <div class="app-container">
    <!-- 操作栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['saleline:saleline:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['saleline:saleline:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['saleline:saleline:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['saleline:saleline:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="salelineList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="出库记录ID" align="center" prop="salseId" />
      <el-table-column label="库存记录ID" align="center" prop="materialStockId" />
      <el-table-column label="产品物料ID" align="center" prop="itemId" />
      <el-table-column label="产品物料编码" align="center" prop="itemCode" />
      <el-table-column label="产品物料名称" align="center" prop="itemName" />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="出库数量" align="center" prop="quantitySalse" />
      <el-table-column label="批次号" align="center" prop="batchCode" />
      <el-table-column label="仓库编码" align="center" prop="warehouseCode" />
      <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="库区编码" align="center" prop="locationCode" />
      <el-table-column label="库区名称" align="center" prop="locationName" />
      <el-table-column label="库位编码" align="center" prop="areaCode" />
      <el-table-column label="库位名称" align="center" prop="areaName" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['saleline:saleline:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['saleline:saleline:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/修改销售出库行对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="salelineRef" :model="form" :rules="rules" label-width="100px">
        <!-- 第一行：产品物料编码（带同行搜索按钮） + 产品物料名称 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品物料编码" prop="itemCode" label-width="120px">
              <div style="display: flex; align-items: center;">
                <el-input 
                  v-model="form.itemCode" 
                  placeholder="请输入产品物料编码" 
                  style="flex: 1; margin-right: 8px;" 
                  :disabled="isSelectProduct" />
                <el-button 
                  :icon="Search" 
                  @click="dialogProductVisible = true" 
                  type="primary" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品物料名称" prop="itemName">
              <el-input v-model="form.itemName" placeholder="请输入产品物料名称" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：规格型号 + 单位 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="form.specification" placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unitOfMeasure">
              <el-input v-model="form.unitOfMeasure" placeholder="请输入单位" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行：出库数量 + 批次号 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出库数量" prop="quantitySalse">
              <div style="display: flex; align-items: center;">
                <el-input 
                  v-model="form.quantitySalse" 
                  placeholder="请输入出库数量" 
                  type="number" 
                  min="1"
                  @input="handleQuantityInput"
                  style="flex: 1;"
                />
                <span v-if="maxQuantity > 0" style="margin-left: 10px; color: #666;">
                  最大可出库量：{{ maxQuantity }}
                </span>
              </div>
            </el-form-item>
          </el-col>
                 <el-col :span="12">
            <el-form-item label="仓库名称" prop="warehouseName">
              <el-input v-model="form.warehouseName" placeholder="请输入仓库名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行：库区编码 + 库区名称 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库区名称" prop="locationName">
              <el-input v-model="form.locationName" placeholder="请输入库区名称" />
            </el-form-item>
          </el-col>
             <el-col :span="12">
            <el-form-item label="库位名称" prop="areaName">
              <el-input v-model="form.areaName" placeholder="请输入库位名称" />
            </el-form-item>
          </el-col>
        </el-row>

  


        <!-- 第七行：备注 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <!-- 底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 产品物料选择弹窗（整合分类筛选） -->
    <el-dialog v-model="dialogProductVisible" title="选择产品物料" width="900px" append-to-body>
      <el-container>
        <!-- 左侧：物料分类树 -->
        <el-aside width="200px" style="background-color: #f5f7fa; padding: 10px;">
          <el-table
            style="border: none;"
            :data="type1List"
            row-key="itemTypeId"
            :default-expand-all="isExpandAll"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            @row-click="handleCategoryClick"
          >
            <el-table-column align="center" prop="itemTypeName" label="物料分类" />
          </el-table>
        </el-aside>

        <!-- 右侧：物料列表（带搜索+分页） -->
        <el-main style="padding: 10px;">
          <el-form :model="productQuery" ref="productQueryRef" :inline="true" label-width="80px" class="mb8">
            <el-form-item label="物料编码" prop="itemCode">
              <el-input
                v-model="productQuery.itemCode"
                placeholder="请输入物料编码"
                clearable
                @keyup.enter="getProductList"
              />
            </el-form-item>
            <el-form-item label="物料名称" prop="itemName">
              <el-input
                v-model="productQuery.itemName"
                placeholder="请输入物料名称"
                clearable
                @keyup.enter="getProductList"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="getProductList">搜索</el-button>
              <el-button icon="Refresh" @click="resetProductQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-table
            :data="productList"
            border
            @selection-change="handleProductSelection"
            style="width: 100%;"
            v-loading="productLoading"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column label="物料编码" align="center" prop="itemCode" />
            <el-table-column label="物料名称" align="center" prop="itemName" />
            <el-table-column label="规格型号" align="center" prop="specification" />
            <el-table-column label="单位" align="center" prop="unitOfMeasure" />
            <el-table-column label="在库数量" align="center" prop="quantityOnhand" />
            <el-table-column label="批次号" align="center" prop="batchCode" />
            <el-table-column label="仓库名称" align="center" prop="warehouseName" />
          </el-table>

          <pagination
            v-show="productTotal>0"
            :total="productTotal"
            v-model:page="productQuery.pageNum"
            v-model:limit="productQuery.pageSize"
            @pagination="getProductList"
            style="margin-top: 10px;"
          />
        </el-main>
      </el-container>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmProduct">确定选择</el-button>
          <el-button @click="dialogProductVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Saleline">
// ====================================== 1. 依赖导入 ======================================
// 核心API
import { listSaleline, getSaleline, delSaleline, addSaleline, updateSaleline } from "@/api/saleline/saleline"
import { listType1 } from "@/api/type1/type1"
import { listStock } from '@/api/stock/stock'

// 组件与图标
import Pagination from "@/components/Pagination"
import RightToolbar from "@/components/RightToolbar"
import { Search, Edit, Delete, Download } from "@element-plus/icons-vue"

// Vue工具
import { getCurrentInstance, ref, reactive, toRefs } from "vue"

// ====================================== 2. 响应式变量定义 ======================================
// 全局实例
const { proxy } = getCurrentInstance()

// ---------------------- 基础列表状态 ----------------------
const salelineList = ref([]) // 销售出库行列表数据
const loading = ref(true)     // 列表加载状态
const showSearch = ref(true)  // 搜索栏显隐
const total = ref(0)          // 列表总数
const ids = ref([])           // 选中行ID集合
const single = ref(true)      // 是否单选（控制修改按钮禁用）
const multiple = ref(true)    // 是否无选择（控制删除按钮禁用）

// ---------------------- 弹窗相关状态 ----------------------
const open = ref(false)                  // 新增/修改弹窗显隐
const title = ref("")                    // 弹窗标题
const dialogProductVisible = ref(false)  // 产品选择弹窗显隐
const isSelectProduct = ref(false)       // 是否已选择产品（控制编码输入框禁用）

// ---------------------- 出库量限制相关 ----------------------
const maxQuantity = ref(0) // 最大可出库量（等于选中物料的在库数量）

// ---------------------- 表单与查询参数 ----------------------
const data = reactive({
  form: { // 新增/修改表单数据
    lineId: null,
    salseId: null,
    materialStockId: null,
    itemId: null,
    itemCode: null,
    itemName: null,
    specification: null,
    unitOfMeasure: null,
    quantitySalse: null,
    batchCode: null,
    warehouseId: null,
    warehouseCode: null,
    warehouseName: null,
    locationId: null,
    locationCode: null,
    locationName: null,
    areaId: null,
    areaCode: null,
    areaName: null,
    remark: null,
  },
  queryParams: { // 销售出库行列表查询参数
    pageNum: 1,
    pageSize: 10,
    salseId: null,
    materialStockId: null,
    itemId: null,
    itemCode: null,
    itemName: null,
    specification: null,
    unitOfMeasure: null,
    quantitySalse: null,
    batchCode: null,
    warehouseId: null,
    warehouseCode: null,
    warehouseName: null,
    locationId: null,
    locationCode: null,
    locationName: null,
    areaId: null,
    areaCode: null,
    areaName: null,
  },
  rules: { // 表单验证规则
    itemCode: [
      { required: true, message: "产品物料编码不能为空", trigger: "blur" }
    ],
    quantitySalse: [
      // { required: true, message: "出库数量不能为空", trigger: "blur" },
      // { type: "number", min: 1, message: "出库数量必须大于0", trigger: "blur" },
      // 最大值校验（依赖maxQuantity）
      { 
        validator: (rule, value, callback) => {
          if (maxQuantity.value > 0 && Number(value) > maxQuantity.value) {
            callback(new Error(`出库数量不能超过最大可出库量 ${maxQuantity.value}`))
          } else {
            callback()
          }
        },
        trigger: ["blur", "change"]
      }
    ],
  }
})
const { queryParams, form, rules } = toRefs(data)

// ---------------------- 产品选择弹窗相关变量 ----------------------
// 分类树数据
const type1List = ref([])         // 物料分类树
const isExpandAll = ref(true)     // 分类树默认全展开

// 物料列表数据
const productList = ref([])       // 物料列表
const productTotal = ref(0)       // 物料总数
const productLoading = ref(false) // 物料列表加载状态
const selectedProduct = ref(null) // 选中的物料

// 物料查询参数（带分类筛选）
const productQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  itemTypeId: 1, // 默认选中第一个分类
  itemCode: null,
  itemName: null,
  batchCode: null,
  warehouseName: null
})
//父传子数据获取
const props = defineProps({
  currentSalseId:{
    type:[Number,String],
    required:true,
    default:null
  }
})
const isMounted = ref(false)
onMounted(()=>{
  isMounted.value=true
});
watch(()=>{
  ()=>props.currentSalseId;
  (newVal) => {
    console.log("父组件传递的工序ID：", newVal); // 切换工序时，日志应同步变化
    if (isMounted.value && newVal) { // 新增isMounted判断
      getList();
    }
  },
   { immediate: true }
})
// ====================================== 3. 核心数据加载逻辑 ======================================
/**
 * 1. 查询销售出库行列表
 */
function getList() {
  loading.value = true
    const params ={
    ...queryParams.value,
    salseId:props.currentSalseId
  }
  listSaleline(params).then(response => {
    salelineList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/**
 * 2. 加载物料分类树（产品选择弹窗用）
 */
function getType1List() {
  listType1({}).then(response => {
    // 复用全局树形结构处理函数（与参考组件一致）
    type1List.value = proxy.handleTree(response.data, "itemTypeId", "parentTypeId")
  })
}

/**
 * 3. 获取物料列表（产品选择弹窗用，带分类筛选）
 */
function getProductList() {
  productLoading.value = true
  listStock(productQuery).then(response => {
    productList.value = response.rows
    productTotal.value = response.total
    productLoading.value = false
  }).catch(err => {
    console.error("获取物料列表失败：", err)
    productLoading.value = false
    proxy.$modal.msgError("物料数据加载失败，请重试")
  })
}

// ====================================== 4. 表单操作逻辑 ======================================
/**
 * 表单重置
 */
function reset() {
  form.value = {
    lineId: null,
    salseId: props.currentSalseId,
    materialStockId: null,
    itemId: null,
    itemCode: null,
    itemName: null,
    specification: null,
    unitOfMeasure: null,
    quantitySalse: null,
    batchCode: null,
    warehouseId: null,
    warehouseCode: null,
    warehouseName: null,
    locationId: null,
    locationCode: null,
    locationName: null,
    areaId: null,
    areaCode: null,
    areaName: null,
    remark: null,
  }
  isSelectProduct.value = false
  maxQuantity.value = 0 // 重置最大可出库量
  proxy.resetForm("salelineRef")
}

/**
 * 提交表单（新增/修改）
 */
function submitForm() {
  proxy.$refs["salelineRef"].validate(valid => {
    if (valid) {
      // 打印提交数据，检查关键字段是否存在
      console.log("提交的出库数据：", form.value)
      
      const request = form.value.lineId ? updateSaleline : addSaleline
      request(form.value)
        .then(() => {
          proxy.$modal.msgSuccess(form.value.lineId ? "修改成功" : "新增成功")
          open.value = false
          getList() // 刷新销售出库列表
        })
        .catch(error => {
          // 捕获提交错误，打印详细信息
          console.error("出库数据提交失败：", error.response || error)
          proxy.$modal.msgError("提交失败，请检查库存关联或联系管理员")
        })
    }
  })
}

// ====================================== 5. 交互事件处理 ======================================
/**
 * 取消弹窗
 */
function cancel() {
  open.value = false
  reset()
}

/**
 * 搜索按钮操作（销售出库行列表）
 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/**
 * 重置搜索表单（销售出库行列表）
 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/**
 * 表格多选框选中事件
 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.lineId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/**
 * 新增销售出库行
 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加产品销售出库行"
  isSelectProduct.value = false
}

/**
 * 修改销售出库行
 */
function handleUpdate(row) {
  reset()
  const _lineId = row.lineId || ids.value
  getSaleline(_lineId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改产品销售出库行"
    isSelectProduct.value = true // 编辑时禁止重新选择产品
    
    // 如果有库存信息，设置最大可出库量
    if (response.data.quantityOnhand) {
      maxQuantity.value = Number(response.data.quantityOnhand)
    }
  })
}

/**
 * 删除销售出库行
 */
function handleDelete(row) {
  const _lineIds = row.lineId || ids.value
  proxy.$modal.confirm(`是否确认删除产品销售出库行编号为"${_lineIds}"的数据项？`).then(() => {
    return delSaleline(_lineIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/**
 * 导出销售出库行
 */
function handleExport() {
  proxy.download('saleline/saleline/export', {
    ...queryParams.value
  }, `saleline_${new Date().getTime()}.xlsx`)
}

/**
 * 出库数量输入监听（实时限制最大量）
 */
function handleQuantityInput() {
  // 转换为数字（避免字符串类型的比较错误）
  const inputVal = Number(form.value.quantitySalse) || 0
  // 最大可出库量大于0时才校验
  if (maxQuantity.value > 0 && inputVal > maxQuantity.value) {
    proxy.$modal.msgWarning(`出库数量不能超过最大可出库量 ${maxQuantity.value}`)
    // 强制重置为最大可出库量
    form.value.quantitySalse = maxQuantity.value.toString()
  }
}

// ---------------------- 产品选择弹窗交互 ----------------------
/**
 * 分类树点击事件（筛选物料）
 */
function handleCategoryClick(row) {
  productQuery.itemTypeId = row.itemTypeId
  productQuery.pageNum = 1
  getProductList()
}

/**
 * 物料表格选择事件
 */
const handleProductSelection = (selection) => {
  selectedProduct.value = selection.length > 0 ? selection[0] : null
}

/**
 * 重置物料搜索参数
 */
function resetProductQuery() {
  proxy.resetForm("productQueryRef")
  productQuery.itemTypeId = 1
  productQuery.pageNum = 1
  getProductList()
}

/**
 * 确认选择产品（核心优化：回填所有关联字段）
 */
const confirmProduct = () => {
  if (!selectedProduct.value) {
    proxy.$modal.msgWarning("请选择产品物料")
    return
  }

  const selected = selectedProduct.value
  // 1. 回填基础字段
  form.value.itemId = selected.itemId
  form.value.itemCode = selected.itemCode
  form.value.itemName = selected.itemName
  form.value.specification = selected.specification
  form.value.unitOfMeasure = selected.unitOfMeasure
  form.value.materialStockId = selected.materialStockId // 关键：关联库存记录的ID
  form.value.batchCode = selected.batchCode
  form.value.warehouseId = selected.warehouseId
  form.value.warehouseCode = selected.warehouseCode
  form.value.warehouseName = selected.warehouseName
  form.value.locationId = selected.locationId
  form.value.locationCode = selected.locationCode
  form.value.locationName = selected.locationName
  form.value.areaId = selected.areaId
  form.value.areaCode = selected.areaCode
  form.value.areaName = selected.areaName

  // 2. 同步最大可出库量（转换为数字，避免字符串比较）
  maxQuantity.value = Number(selected.quantityOnhand) || 0
  if (maxQuantity.value <= 0) {
    proxy.$modal.msgWarning("该物料当前无库存，无法出库")
    return
  }

  isSelectProduct.value = true
  dialogProductVisible.value = false
}

// ====================================== 6. 初始化 ======================================
// 1. 加载销售出库行列表
getList()

// 2. 加载物料分类树（产品选择弹窗用）
getType1List()

// 3. 打开产品选择弹窗时加载物料列表
const openProductDialog = () => {
  dialogProductVisible.value = true
  getProductList()
}
</script>

<style scoped>
.app-container {
  padding: 16px;
}
.mb8 {
  margin-bottom: 8px;
}
</style>
